package com.dao;

import com.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author: Zs
 * @date:2022/6/22 23:21
 */
public class UserDao {
    private SqlSessionFactory sqlsessionFactory;

    public UserDao(String configPath) throws IOException {
        //加载mybatis-config配置文件
        InputStream is = Resources.getResourceAsStream(configPath);
        //创建SqlSessionFactory对象与数据库创建连接
        InputStream inputStream = Resources.getResourceAsStream(configPath);
        sqlsessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }

    public List<User> findAll() {
        SqlSession sqlSession = sqlsessionFactory.openSession();
        List<User> studentList = sqlSession.selectList("findAll");
        sqlSession.close();
        return studentList;
    }

    public int addUser(User user) {
        SqlSession sqlSession = sqlsessionFactory.openSession();
        int rowsAffected = sqlSession.insert("insert", user);
        sqlSession.commit();
        sqlSession.close();
        return rowsAffected;
    }

    public int deleteUser(int id) {
        SqlSession sqlSession = sqlsessionFactory.openSession();
        int rowsAffected = sqlSession.delete("delete",id);
        sqlSession.commit();
        sqlSession.close();
        return rowsAffected;
    }


}
